/*
 * Copyright 2019 The ZuSmart Project
 *  
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zusmart.base.logging;

import com.zusmart.base.logging.support.JdkLoggerFactory;
import com.zusmart.base.logging.support.Log4J2LoggerFactory;
import com.zusmart.base.logging.support.Log4JLoggerFactory;
import com.zusmart.base.logging.support.Slf4JLoggerFactory;

/**
 * @author Administrator
 *
 */
public abstract class LoggerFactory {

	private static volatile LoggerFactory defaultLoggerFactory;

	private static LoggerFactory createDefaultLoggerFactory(String loggerName) {
		LoggerFactory loggerFactory = null;
		try {
			loggerFactory = new Slf4JLoggerFactory();
			loggerFactory.createLogger(loggerName).debug("Using SLF4j as the default logging framework");
		} catch (Throwable t) {
			try {
				loggerFactory = new Log4JLoggerFactory();
				loggerFactory.createLogger(loggerName).debug("Using LOG4J as the default logging framework");
			} catch (Throwable tt) {
				try {
					loggerFactory = new Log4J2LoggerFactory();
					loggerFactory.createLogger(loggerName).debug("Using LOG4J2 as the default logging framework");
				} catch (Throwable ttt) {
					loggerFactory = new JdkLoggerFactory();
					loggerFactory.createLogger(loggerName).debug("Using java.util.logging as the default logging framework");
				}
			}
		}
		return loggerFactory;
	}

	public static LoggerFactory getDefaultLoggerFactory() {
		if (null == defaultLoggerFactory) {
			defaultLoggerFactory = createDefaultLoggerFactory(LoggerFactory.class.getName());
		}
		return defaultLoggerFactory;
	}

	public static void setDefaultLoggerFactory(LoggerFactory defaultLoggerFactory) {
		if (null == defaultLoggerFactory) {
			throw new NullPointerException("defaultLoggerFactory");
		}
		LoggerFactory.defaultLoggerFactory = defaultLoggerFactory;
	}

	public static Logger getLogger(Class<?> clazz) {
		return getLogger(clazz.getName());
	}

	public static Logger getLogger(String name) {
		return getDefaultLoggerFactory().createLogger(name);
	}

	protected abstract Logger createLogger(String name);

}